package com.sendemail.thread;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.annotation.PostConstruct;

/**
 * @author MeowParse
 * @date 2017/9/4.
 */
@Component
public class ListenerThread extends Thread {

	private EmailThread emailThread;
	@Autowired
	private JedisPool jedisPool;

	private static ListenerThread listenerThread;
	private Jedis redis;//= new Jedis(Constants.redisHost, Constants.redisPort,Constants.redisTimeOut);

	@PostConstruct     //关键二   通过@PostConstruct 和 @PreDestroy 方法 实现初始化和销毁bean之前进行的操作
	public void init() {
		listenerThread = this;
		listenerThread.jedisPool = this.jedisPool;
	}

	public ListenerThread(EmailThread emailThread) {
		this.emailThread = emailThread;
	}

	@Override
	public void run() {
		redis = listenerThread.jedisPool.getResource();
		while (true) {
			if (!emailThread.isAlive()) {
				if (emailThread.getExportModel() != null) {
					String counter = emailThread.getExportModel().getCounter();
					if (redis.exists(counter)) {
						int count = Integer.parseInt(redis.get(counter));
						if (count > 0) {
							count--;
							redis.set(counter, count + "");
						}
					}
					EmailThread emailThread = new EmailThread();
					emailThread.start();
					this.emailThread = emailThread;
				}
				try {
					sleep(600000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
